<template>
  <div class="chart-container">
    <el-card>
       <div class="filter-container">
        <el-select
          v-model="selectedDealer"
          placeholder="Select the distributor"
          @change="handleDealerChange"
          style="width: 300px; margin-bottom: 20px;"
          size="large"
          v-if="auth===10"
        >
          <el-option label="All" value="" />
          <el-option label="Dreams Limited" value="Dreams Limited" />
          <el-option label="TrueMotion" value="TrueMotion" />
        </el-select>
      </div>
      <div class="chart-wrapper">
        <el-empty v-if="faultData.length === 0" style="height: 500px;" description="No data available" />
        <div v-else ref="chartRef" style="height: 500px;"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
  import { ref,onMounted, watch, nextTick,computed } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts';
  import { useLoading } from '../../utils/loading';
  import { useSidebarStore } from '../../store/sidebarStore';
  import { useManageStore } from '../../store/manageStore';
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL

  const selectedDealer = ref(null) // 当前选中的经销商
  const faultData = ref([])
  const chartRef = ref(null)
  let chartInstance = null
  const sidebarStore = useSidebarStore();
  const manageStore = useManageStore();
  const isCollapse = computed(() => sidebarStore.isCollapse);
  const auth = computed(() => manageStore.auth)
  const dealer = computed(() => manageStore.dealer)
  watch(isCollapse,async(newVal) => {
    await getFault();
  },{ flush: 'post' }) 
  onMounted(() => {
    getFault()
  })

  // 处理经销商选择变化
  const handleDealerChange = () => {
    getFault()
  }

  const getFault = async() => {
    showLoading('loading...')
    try{
      const res = await axios.get(`${BASE_URL}manage/countModelFault`,{
        params:{
          dealer:auth === 10? dealer.value : selectedDealer.value 
        }
      })
      if(res.data && res.data.data) {
        faultData.value = res.data.data.map(item => ({
          name:item.title,
          value:item.num
        }))
      }
    }catch(error){
      ElMessage.error('Failed to obtain fault data');
    }finally {
      hideLoading();
    }
  }
  
  // 监听数据变化并渲染图表
  watch(faultData,(newVal) => {
    if(newVal.length > 0) {
      nextTick(() => {
        initChart()
      })
    }
  },{ deep:true })

  const initChart = () => {
    if(!chartRef.value) return

    //销毁之前的图表实例
    if(chartInstance) {
      chartInstance.dispose();
    }

    //初始化新表图
    chartInstance = echarts.init(chartRef.value)

    // 动态计算柱子宽度
    const getDynamicBarWidth = (visibleCount) => {
      // 当可见柱子≤6时60px，>6时按比例计算(最大60%)
      return visibleCount <= 6 ? '100px' : Math.min(60, 100 / visibleCount * 60) + '%';
    };

    const option = {
      title: {
        text: 'Fault model distribution',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c}person'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: faultData.value.map(item => item.name),
        axisLabel: {
          rotate: 30, // Rotate labels if they're long
          interval: 0 // Show all labels
        }
      },
      yAxis: {
        type: 'value',
        name: 'Fault Count'
      },
      dataZoom: [
        {
          type: 'slider', // 滑动条型 dataZoom
          show: true,
          xAxisIndex: [0], // 控制 x 轴
          start: 0,        // 默认起始位置 0%
          end: 60,         // 默认结束位置 80%
          height: 20,      // 滚动条高度
          bottom: 5,       // 距离底部位置
          fillerColor: '#1890ff', // 滚动条填充色
          borderColor: 'transparent',
          handleStyle: {
            color: '#1890ff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          emphasis: {
            handleStyle: {
              color: '#0056b3'
            }
          }
        }
      ],
      series: [{
        name: 'Fault Count',
        type: 'bar',
        barWidth: getDynamicBarWidth(faultData.value.length),
        barGap: '20', // 柱子间间距
        barCategoryGap: '0', // 类目间柱形间距
        data: faultData.value.map(item => item.value),
        itemStyle: {
          color: function(params) {
            // Custom color for each bar
            const colorList = ['#FF0000', '#FFA500', '#FFFF00', '#008000', '#0000FF', '#4B0082', '#FF00FF'];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [5, 5, 0, 0] // Rounded top corners
        },
        label: {
          show: true,
          position: 'top'
        }
      }]
    }
    chartInstance.setOption(option);
  
     // 更精确的可见区域监听
    let lastVisibleCount = faultData.value.length;

    chartInstance.on('rendered', function() {
      const model = chartInstance.getModel();
      const xAxisModel = model.getComponent('xAxis', 0);
      
      if (xAxisModel) {
        const axis = xAxisModel.axis;
        const bandWidth = axis.getBandWidth(); // 获取当前每个柱子的实际像素宽度
        const visibleCount = Math.floor(chartRef.value.offsetWidth / bandWidth);
        
        if (visibleCount !== lastVisibleCount) {
          lastVisibleCount = visibleCount;
          chartInstance.setOption({
            series: [{
              barWidth: getDynamicBarWidth(visibleCount)
            }]
          });
        }
      }
    });

     // 同时保留dataZoom监听作为备用
    chartInstance.on('dataZoom', function() {
      const option = chartInstance.getOption();
      const currentZoom = option.dataZoom[0];
      const visibleCount = Math.floor(
        faultData.value.length * (currentZoom.end - currentZoom.start) / 100
      );
      
      if (visibleCount !== lastVisibleCount) {
        lastVisibleCount = visibleCount;
        chartInstance.setOption({
          series: [{
            barWidth: getDynamicBarWidth(visibleCount)
          }]
        });
      }
    });

    // 响应式调整
    window.addEventListener('resize', function() {
      chartInstance.resize();
    });
  }

</script>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 500px;
  }
  .chart-wrapper {
    width: 100%;
    height: 100%;
  }
</style>